const http = require("http");
const fs = require("fs");
const path = require("path");
const serve = http.createServer();
const querystring = require("querystring");
var dirname = "static"
var users = [{
    name: "张三",
    info: "哈哈哈"
}];
serve.on("request", (req, res) => {
    var filepath = path.join(__dirname, dirname, req.url)
    console.log(req.url);
    if (req.url == "/") {
        res.setHeader('Content-Type', "text/html;charset=utf-8");
        filepath = path.join(__dirname, dirname, "index.html")
        var data2 = fs.readFileSync(filepath, 'utf-8')
        var html = '';
        users.forEach(function (list) {
            html += `<li><span>${list.name}:</span>${list.info}</li>`
        })
        var newhtml = data2.toString().replace('^_^', html).trim()
        res.end(newhtml);
    }
    if (req.url == "/favicon.ico") {
        filepath = path.join(__dirname, dirname, "img", "120px-八奈見杏菜.jpg")
    }
    if (req.url.indexOf('name') != -1 && req.method == "GET") {
        let url = new URL(req.url, "http://localhost:3000/");
        console.log(url.searchParams.get("name"));
        console.log(url.searchParams.get("info"));
        if (url.searchParams.get("name")) {
            users.push({
                name: url.searchParams.get("name"),
                info: url.searchParams.get("info")
            })
            //重定向到首页
            res.statusCode = 302;
            res.setHeader('location', '/')
            res.end();
        }
        else {
            res.end('你提交的内容为空')
        }
    }
    if (req.method == "POST") {
        var body = "";
        req.on('data', (chunk) => {
            body += chunk;
        });
        req.on('end', () => {
            console.log(querystring.parse(body).name);
            console.log(querystring.parse(body).info);
            if (querystring.parse(body).name) {
                users.push({
                    name: querystring.parse(body).name,
                    info: querystring.parse(body).info
                })
                // //重定向到首页
                res.statusCode = 302;
                // res.setHeader('location', '/');
                res.end();
            }
            else {
                res.end('你提交的内容为空')
            }
        });
       
    }
    fs.readFile(filepath,(err,data)=>{ 
        if(err){
            res.end(err);
        }else{
            res.end(data);
        }
    });
});

serve.listen("3000", () => {
    console.log("服务启动成功,请访问http://10.10.49.42:3000/,或http://127.0.0.1:3000/,或http://localhost:3000/");
})